<?php
# User session management
require_once('includes/user_manage.php');

$user->order->set_from_array($_POST); // address_id, phone, sec_phone, comments, payment_method_id, shipping_type_id
$user->order->status=1;
$user->order->delivery=new delivery();
$user->order->delivery->phone=$user->order->phone;
if ($user->order->sec_phone) $user->order->delivery->sec_phone=$user->order->sec_phone;
$user->order->delivery->shipping_type=new shipping_type();
$user->order->delivery->shipping_type->id=$user->order->shipping_type_id;
$user->order->delivery->shipping_type->db_load();
$user->order->payment=new payment();
$user->order->payment->method=new payment_method();
$user->order->payment->method->id=$user->order->payment_method_id;
$user->order->payment->method->db_load();
$user->order->delivery->address=new address();
$user->order->delivery->address->user_id=$user->id;
$user->order->delivery->address->set_from_array($_POST);
$user->order->price=$user->order->subTotal + $user->order->delivery->shipping_type->price + $user->order->payment->method->price;
// We check if there were a default user address.
if ($user->order->address_id > 0) {
	$user->order->delivery->address->id=$user->order->address_id;
	$user->order->delivery->address->db_update();
}
// If it is not defaul address that means the user have never got any address so we insert it.
else {
	$user->order->delivery->address->db_insert();
	$user->order->address_id=$user->order->delivery->address->id;
	// We also set user data, because there were never settled
	$user->set_from_array($_POST); // firstname, lastname, phone, sec_phone
	$user->address_id=$user->order->address_id;
	$user->db_update();
}
// We insert now the order at the orders table
$user->order->db_insert();

// We insert the order cart items into the database table orders_items
foreach ($user->order->items as $item) {
	$item->order_id=$user->order->id; // First we set the property order_id at the item
	$item->db_insert();
}
$_SESSION["ser_user"]=serialize($user);
if ($user->order->id) {
?>
<div class="note">
	El pedido ha sido recibido correctamente.
</div>
<script type="text/javascript">
//We update the user name
document.getElementById("connectStatusName").innerHTML = "<?php echo $user->firstname." ".$user->lastname ?>";
// We empty the shopping cart
myOrder.items=new Array();
myOrder.sumPrice();
myOrder.refreshItemsListView("cartItemsList");
</script>
<?php
}
else {
?>
<div class="note">
	El pedido NO ha sido realizado correctamente.
</div>
<p>
	Por favor contacte con nosotros para indicarnos este echo.
</p>
<?php
}
// We end up showing the usser area, that will shoy a notification of the last order maden
include($server->get_path_name('user_area.php'));
?>
